/**
 * Created by adeline on 2017/7/10.
 */
import Vue from 'vue'
import sessionDAO from 'common/sessionDAO'
import {setToken, saveyyzToken, setTouristParam} from 'common/common.util'

/**
 * 远程接口数据访问对象
 *
 * @class common.remoteDAO
 */
const RemoteDAO = {}
const Bridge = window.Bridge || {}
const decrypt = window.decrypt || {}
const md5 = window.md5 || {}

/**
 * 登录
 * @param callback
 */
RemoteDAO.callNativeLogin = function (tg) {
  let tgCode = tg ? '?tgCode=' + tg : ''
  let registerUrl = 'gtjanrng://register' + tgCode
  console.log(registerUrl)
  return new Promise((resolve, reject) => {
    Bridge.callByJsUrl(registerUrl, response => {
      if (Number(response.error) === 1) {
        console.log('原生登录-error：', response.data)
        reject(new Error(response.data))
      } else {
        console.log('原生登录-data：', response)
        var userCode = response.data.user_code
        var nickName = response.data.nick_name
        sessionDAO.setUserCode(userCode)
        sessionDAO.setNickname(nickName)
        document.getElementsByTagName('meta')['yyzshareurl']['content'] = 'http://dl.app.gtja.com/nrng/newShares/gldh-game-award.html?source=squarePage&usercode=' + sessionDAO.getUserCode()
        resolve(Object.assign({}, response))
      }
    })
  })
}

/**
 * 将需要分享的数据传送到后台接口
 * @param pagename
 * @param callback
 */
RemoteDAO.sendShareData = function (pagename) {
  return new Promise((resolve, reject) => {
    let shareContent = ''
    if (pagename) {
      shareContent = localStorage.getItem(pagename) || sessionStorage.getItem(pagename)
    }
    let usercode = sessionDAO.getUserCode() || parseInt(Math.random() * 100000)
    let url = 'https://dl.app.gtja.com/yyz/data/api/niurenshare/share'
    Vue.prototype.$http.post(url, {usercode: usercode, type: pagename, content: shareContent})
      .then(result => {
        resolve(result)
      })
      .catch(error => reject(new Error(error)))
  })
}

/**
 *  分享
 * @param title     分享题目
 * @param content   分享的内容
 * @param linkurl   链接
 * @param moments 表示分享到朋友圈是使用title还是content,或是都拼在一起  title/content/all
 * @param icon 表示分享出去的图片地址
 */
RemoteDAO.share = function (args) {
  console.log(args)
  window.location.href = 'gtjayyznormal://yyzShare?title=' + args.title + '&icon=' + args.icon + '&content=' + args.content + '&moments=' + args.moments + '&linkurl=' + args.linkurl
}

/**
 * 12000004：获取当前用户 userCode
 * @method callUC12000004
 * @param callback 回调函数
 */
RemoteDAO.callUC12000004 = function () {
  return new Promise((resolve, reject) => {
    Bridge.callByJS({
      callback: function (response) {
        if (response.error === '0') {
          let result = decrypt.json2(response.data)
          let object = JSON.parse(result)
          response.data = object
          console.log('12000004-获取当前用户-data:' + object.body[0].USER_CODE)
          resolve(object.body[0].USER_CODE)
        } else {
          console.log('12000004-获取当前用户-error:', response.data)
          reject(new Error(response.data))
        }
      },
      'id': 'h5',
      'tranCode': 'UC12000004',
      'jsToken': '12000004',
      'isEncrypt': 'false',
      'transmitMode': 'get',
      'param': {
        'OP_SITE': '127.0.0.1',
        'OP_PROGRAM': '',
        'BRANCH_NO': '0',
        'TOKEN_SERIAL_NO': '0',
        'USER_TOKEN': '',
        'func_id': '12000004',
        'CUST_CODE': '',
        'USER_CODE': '0',
        'PASSWORD': '',
        'terminal_source': '02' // 必须加
      },
      'localParameter': {'mobile': 'ACCT_CODE,phone_no,mobile', 'password': 'stock_pwd'}
    })
  })
}

/**
 * 公告接口
 * @param relationId   团队赛的id
 */
RemoteDAO.callUC12000054 = function (params) {
  return new Promise((resolve, reject) => {
    var paramData = {
      'FUNC_ID': '12000054',
      'OP_SITE': '127.0.0.1',
      'OP_PROGRAM': '',
      'OP_CODE': '8888',
      'BRANCH_NO': '0',
      'PASSWORD': '',
      'USER_TOKEN': '',
      'TOKEN_SERIAL_NO': '0',
      'BUSIN_TYPE': 'NRNG',
      'RELATION_ID': params.relationId + ''
    }
    let param = setToken(paramData)
    let bridgeParam = {
      callback: function (response) {
        if (response.error === '0') {
          var result = decrypt.json2(response.data)
          var object = JSON.parse(result)
          response.data = object
          // 增加存入token的逻辑
          saveyyzToken(JSON.parse(result).header)
          console.log('12000054-公告接口-data:', response)
          resolve(Object.assign({}, response))
        } else {
          console.log('12000054-公告接口-error:', response)
          reject(new Error(response.data))
        }
      },
      'id': 'nrng_yh',
      'tranCode': 'UC12000054',
      'jsToken': 'UC12000054',
      'isEncrypt': 'false',
      'transmitMode': 'get'
    }
    let finalParam = setTouristParam(param, bridgeParam)
    Bridge.callByJS(finalParam)
  })
}

/**
 * 12000104：用户资料查询
 * @param userCode
 * @param callback
 */
RemoteDAO.callUC12000104 = function (userCode) {
  return new Promise((resolve, reject) => {
    // 设置md5验证
    let token = md5('127.0.0.1M' + userCode + '0')
    let paramData = {
      'OP_SITE': '127.0.0.1',
      'OP_PROGRAM': '',
      'BRANCH_NO': '0',
      'USER_TOKEN': token,
      'TOKEN_SERIAL_NO': '2016000000000011003000040020000000000000000000000000000000000000001212126868000000000000000000000000',
      'func_id': '12000104',
      'CUST_CODE': '',
      'USER_CODE': userCode + '',
      'PASSWORD': '',
      'BUSIN_TYPE': 'NRNG'
    }
    let param = setToken(paramData)
    Bridge.callByJS({
      callback: function (response) {
        if (response.error === '1') {
          console.log('12000104-用户资料查询-error:', response)
          reject(new Error(response.data))
        } else {
          // 以后要加上判断nickname!==''的判断
          var result = decrypt.json2(response.data)
          var object = JSON.parse(result)
          response.data = object
          console.log('12000104-用户资料查询-data:', response)
          resolve(Object.assign({}, response))
        }
      },
      'id': 'h5',
      'tranCode': 'UC12000104',
      'jsToken': 'UC12000104',
      'isEncrypt': 'false',
      'transmitMode': 'get',
      'param': param
    })
  })
}

/**
 * 12000109： 获取经验值接口
 * @param callback
 */
RemoteDAO.callUC12000109 = function (args) {
  return new Promise((resolve, reject) => {
    Bridge.callByJS({
      callback: function (response) {
        if (response.error === '1') {
          console.log('12000109-用户资料修改-获取积分接口-data:' + response.data)
          reject(new Error(response.data))
        } else {
          var result = decrypt.json2(response.data)
          var object = JSON.parse(result)
          response.data = object
          console.log('12000109-用户资料修改-获取积分接口-data:', response)
          resolve(Object.assign({}, response))
        }
      },
      'id': 'nrng_yh',
      'tranCode': 'UC12000109',
      'jsToken': 'UC12000109',
      'isEncrypt': 'false',
      'transmitMode': 'get',
      'param': {
        'OP_SITE': '127.0.0.1',
        'OP_PROGRAM': '',
        'BRANCH_NO': '0',
        'USER_TOKEN': '',
        'TOKEN_SERIAL_NO': '0',
        'func_id': '12000109',
        'PASSWORD': '',
        'USER_CODE': args.userCode + '',
        'ACTIVITY_CODE': '201709_GLDH',
        'BUSIN_TYPE': 'GLDH',
        'MARK_TYPE': 'ActivitySign'
      },
      'localParameter': {'mobile': 'phone_no', 'password': 'stock_pwd'}
    })
  })
}

/**
 * 12000114： 用户信息查询 网易活动经验值与等级
 * @param
 * @param callback
 */
RemoteDAO.callUC12000114 = function (args) {
  return new Promise((resolve, reject) => {
    Bridge.callByJS({
      callback: function (response) {
        if (response.error === '1') {
          console.log('12000114-用户信息查询 网易活动经验值与等级-error:' + response.data)
          reject(new Error(response.data))
        } else {
          var result = decrypt.json2(response.data)
          var object = JSON.parse(result)
          response.data = object
          console.log('12000114-用户信息查询 网易活动经验值与等级-data:', response)
          resolve(Object.assign({}, response))
        }
      },
      'id': 'nrng_yh',
      'tranCode': 'UC12000114',
      'jsToken': 'UC12000114',
      'isEncrypt': 'false',
      'transmitMode': 'get',
      'param': {
        'OP_SITE': '127.0.0.1',
        'OP_PROGRAM': '',
        'BRANCH_NO': '0',
        'USER_TOKEN': '',
        'TOKEN_SERIAL_NO': '0',
        'func_id': '12000114',
        'PASSWORD': '',
        'USER_CODE': args.userCode + '',
        'BUSIN_TYPE': 'WYHDDJ,WYHDJYZ'
      },
      'localParameter': {'mobile': 'phone_no', 'password': 'stock_pwd'}
    })
  })
}

/**
 * 12000353： 查询每天是否送经验值
 * @param getDate  查询经验值的起始时间
 * @param callback
 */
RemoteDAO.callUC12000353 = function (args) {
  return new Promise((resolve, reject) => {
    Bridge.callByJS({
      callback: function (response) {
        if (response.error === '1') {
          console.log('12000353-查询每天是否送经验值-data:' + response.data)
          reject(new Error(response.data))
        } else {
          var result = decrypt.json2(response.data)
          var object = JSON.parse(result)
          response.data = object
          console.log('12000353-查询每天是否送经验值-data:', response)
          resolve(Object.assign({}, response))
        }
      },
      'id': 'nrng_yh',
      'tranCode': 'UC12000353',
      'jsToken': 'UC12000353',
      'isEncrypt': 'false',
      'transmitMode': 'get',
      'param': {
        'OP_SITE': '127.0.0.1',
        'OP_PROGRAM': '',
        'BRANCH_NO': '0',
        'USER_TOKEN': '',
        'TOKEN_SERIAL_NO': '0',
        'func_id': '12000353',
        'PASSWORD': '',
        'USER_CODE': args.userCode + '',
        'ACTIVITY_CODE': '201709_GLDH',
        'BUSIN_TYPE': 'ActivitySign',
        'GET_DATE': args.getDate + ''
      },
      'localParameter': {'mobile': 'phone_no', 'password': 'stock_pwd'}
    })
  })
}

/**
 * 我的比赛查询,
 * @param userCode
 * @param ACTION_FLAG 0：所有  1：参加   2：创建
 * @param PAGE_SIZE
 * @param PAGE_NO
 * @param totalFlag
 * @param gameKind
 * @param {String} gameID 比赛ID 仅当action flag为1时此game ID用于查询用户是否参加了该比赛
 * @param callback
 */
RemoteDAO.callUC12008303 = function (params) {
  return new Promise((resolve, reject) => {
    // 设置md5验证
    var token = md5('127.0.0.1M' + params.userCode + '0')
    let paramData = {
      'FUNC_ID': '12008303',
      'OP_SITE': '127.0.0.1',
      'OP_PROGRAM': '',
      'BRANCH_NO': '0',
      'PASSWORD': '',
      'USER_TOKEN': token,
      'TOKEN_SERIAL_NO': '2016000000000011003000040020000000000000000000000000000000000000001212126868000000000000000000000000',
      'USER_CODE': params.userCode + '',
      'ACTION_FLAG': params.actionFlag + '',
      'PAGE_SIZE': params.pageSize + '',
      'PAGE_NO': params.pageNo + '',
      'TOTAL_FLAG': params.totalFlag ? params.totalFlag + '' : '',
      'GAME_KIND': params.gameKind ? params.gameKind + '' : '',
      'GAME_ID': params.gameID ? params.gameID : ''
    }
    let param = setToken(paramData)
    Bridge.callByJS({
      callback: function (response) {
        if (response.error === '1') {
          console.log('12008303-我的比赛查询-error:', response)
          reject(new Error(response.data))
        } else {
          // 以后要加上判断nickname!==''的判断
          var result = decrypt.json2(response.data)
          var object = JSON.parse(result)
          response.data = object
          // 增加存入token的逻辑
          saveyyzToken(JSON.parse(result).header)
          console.log('12008303-我的比赛查询-data:', response)
          resolve(Object.assign({}, response))
        }
      },
      'id': 'h5',
      'tranCode': 'UC12008303',
      'jsToken': '2',
      'isEncrypt': 'false',
      'transmitMode': 'get',
      'param': param
    })
  })
}

/**
 * 我参加的比赛资产数据，其中包含排名信息，累计收益率等，返回的数据格式：
 * @param callback
 */
RemoteDAO.callJCL11143 = function (args) {
  return new Promise((resolve, reject) => {
    var paramData = {
      'func_id': '11143',
      'type': 'zmq',
      'game_id': args.gameId + '',
      'client_id': args.userCode + ''
    }
    let param = setToken(paramData)
    let bridgeParam = {
      callback: function (response) {
        if (response.error === '1') {
          console.log('11143-参加的比赛资产数据-data:' + response.data)
          reject(new Error(response.data))
        } else {
          var result = decrypt.json2(response.data)
          var object = JSON.parse(result)
          response.data = object
          saveyyzToken(JSON.parse(result).header)
          console.log('11143-参加的比赛资产数据-data:', response)
          resolve(Object.assign({}, response))
        }
      },
      'id': 'nrng',
      'tranCode': 'JCL11143',
      'jsToken': 'JCL11143',
      'isEncrypt': 'false',
      'transmitMode': 'get'
    }
    let finalParam = setTouristParam(param, bridgeParam)
    Bridge.callByJS(finalParam)
  })
}

/**
 * 查询投票
 * @return {[type]}      [description]
 */
RemoteDAO.callUC12008401 = function (args) {
  return new Promise((resolve, reject) => {
    var paramData = {
      'FUNC_ID': '12008401',
      'OP_SITE': '127.0.0.1',
      'OP_PROGRAM': '',
      'OP_CODE': '8888',
      'BRANCH_NO': '0',
      'PASSWORD': '',
      'USER_TOKEN': '',
      'TOKEN_SERIAL_NO': '0',
      'VOTE_STATUS': args.VOTE_STATUS,
      'BUSIN_TYPE': args.BUSIN_TYPE,
      'PAGE_SIZE': args.PAGE_SIZE,
      'PAGE_NO': args.PAGE_NO
    }
    let param = setToken(paramData)
    let bridgeParam = {
      callback: function (response) {
        if (response.error === '0') {
          var result = decrypt.json2(response.data)
          var object = JSON.parse(result)
          response.data = object
          // 增加存入token的逻辑
          saveyyzToken(JSON.parse(result).header)
          resolve(response)
        } else {
          console.error('12008401-查询投票-error:', response)
          reject(new Error(response.data))
        }
      },
      'id': 'nrng_yh',
      'tranCode': 'UC12008401',
      'jsToken': 'UC12008401',
      'isEncrypt': 'false',
      'transmitMode': 'get'
    }
    let finalParam = setTouristParam(param, bridgeParam)
    Bridge.callByJS(finalParam)
  })
}

/**
 * 投票结果查询
 * @param  {Object} params {VOTE_ID: ''}
 * @return {[type]}      [description]
 */
RemoteDAO.callUC12008402 = function (params) {
  return new Promise((resolve, reject) => {
    var paramData = {
      'FUNC_ID': '12008402',
      'OP_SITE': '127.0.0.1',
      'OP_PROGRAM': '',
      'OP_CODE': '8888',
      'BRANCH_NO': '0',
      'PASSWORD': '',
      'USER_TOKEN': '',
      'TOKEN_SERIAL_NO': '0',
      'VOTE_ID': params.VOTE_ID
      // 'USER_CODE': '1'
    }
    let param = setToken(paramData)
    let bridgeParam = {
      callback: function (response) {
        if (response.error === '0') {
          var result = decrypt.json2(response.data)
          var object = JSON.parse(result)
          response.data = object
          // 增加存入token的逻辑
          saveyyzToken(JSON.parse(result).header)
          resolve(response)
        } else {
          console.error('12008402-查询投票-error:', response)
          reject(new Error(response.data))
        }
      },
      'id': 'nrng_yh',
      'tranCode': 'UC12008402',
      'jsToken': 'UC12008402',
      'isEncrypt': 'false',
      'transmitMode': 'get'
    }
    let finalParam = setTouristParam(param, bridgeParam)
    Bridge.callByJS(finalParam)
  })
}

/**
 * 投票结果提交
 * @param  {Object} params {VOTE_ID: '', RESULT_LIST: [{OPTION_ID: '', OPTION_TEXT: ''}]}
 * @return {[type]}      [description]
 */
RemoteDAO.callUC12008403 = function (params) {
  return new Promise((resolve, reject) => {
    var paramData = {
      'FUNC_ID': '12008403',
      'OP_SITE': '127.0.0.1',
      'OP_PROGRAM': '',
      'OP_CODE': '8888',
      'BRANCH_NO': '0',
      'PASSWORD': '',
      'USER_TOKEN': '',
      'TOKEN_SERIAL_NO': '0',
      'VOTE_ID': params.VOTE_ID,
      'RESULT_LIST': JSON.stringify(params.RESULT_LIST)
      // 'USER_CODE': params.USER_CODE
    }
    let param = setToken(paramData)
    let bridgeParam = {
      callback: function (response) {
        if (response.error === '0') {
          var result = decrypt.json2(response.data)
          var object = JSON.parse(result)
          response.data = object
          // 增加存入token的逻辑
          saveyyzToken(JSON.parse(result).header)
          resolve(response)
        } else {
          console.error('12008403-投票结果提交-error:', response)
          reject(new Error(response.data))
        }
      },
      'id': 'nrng_yh',
      'tranCode': 'UC12008403',
      'jsToken': 'UC12008403',
      'isEncrypt': 'false',
      'transmitMode': 'get'
    }
    let finalParam = setTouristParam(param, bridgeParam)
    Bridge.callByJS(finalParam)
  })
}

RemoteDAO.callUC12008306 = function (args) {
  return new Promise((resolve, reject) => {
    Bridge.callByJS({
      callback: function (response) {
        if (response.error === '1') {
          console.error('12008306-error:', response)
          reject(new Error(response.data))
        } else {
          var result = decrypt.json2(response.data)
          var json = JSON.parse(result)
          response.data = json
          console.log('12008306-data', response)
          resolve(response)
        }
      },
      'id': 'nrng_yh',
      'tranCode': 'GT1003',
      'jsToken': '111',
      'isEncrypt': 'false',
      'transmitMode': 'get',
      'param': {
        'FUNC_ID': '12008306',
        'OP_BRANCH_NO': '0',
        'OP_SITE': '127.0.0.1',
        'OP_PROGRAM': '',
        'BRANCH_NO': '0',
        'PASSWORD': '',
        'USER_CODE': args.userCode + '',
        'USER_TOKEN': '',
        'TOKEN_SERIAL_NO': '0',
        'ACTION_TYPE': args.actionType + '',
        'BUSIN_TYPE': args.businType + '',
        'COMMUNITY_TYPE': args.communityType + '',
        'OBJECT_TYPE': args.objectType + '',
        'RELATION_USER_CODE': '',
        'RELATION_USER_NAME': '',
        'BEGIN_DATE': '',
        'END_DATE': '',
        'COMMUNITY_CONTENT': args.communityContent + '',
        'TOPIC_CODE': args.topicCode + '',
        'TOPIC_NAME': args.topicName + '',
        'SERIAL_NO': ''
      },
      'localParameter': {
        'mobile': 'phone_no',
        'password': 'stock_pwd'
      }
    })
  })
}

RemoteDAO.callUC12008318 = function (params) {
  return new Promise((resolve, reject) => {
    var paramData = {
      'FUNC_ID': '12008318',
      'OP_SITE': '127.0.0.1',
      'OP_PROGRAM': '',
      'OP_CODE': '8888',
      'BRANCH_NO': '0',
      'PASSWORD': '',
      'USER_TOKEN': '',
      'TOKEN_SERIAL_NO': '0',
      'GAME_ID': params.ID + '',
      'PAGE_SIZE': params.PAGE_SIZE + '',
      'PAGE_NO': params.PAGE_NO + '',
      'COMMUNITY_STATUS': '1',
      'OBJECT_TYPE': '9',  // 9用于股林大会的评论查询
      'QUERY_FLAG': params.QUERY_FLAG + '' // 查询标志 1-查个人 0或空－查该比赛的所有评论
    }
    var param = setToken(paramData)
    var bridgeParam = {
      callback: function (response) {
        if (response.error === '0') {
          var result = decrypt.json2(response.data)
          var object = JSON.parse(result)
          response.data = object
          saveyyzToken(JSON.parse(result).header)
          resolve(response)
        } else {
          reject(new Error(response.data))
        }
      },
      'id': 'nrng_yh',
      'tranCode': 'UC12008318',
      'jsToken': 'UC12008318',
      'isEncrypt': 'false',
      'transmitMode': 'get'
    }
    var finalParam = setTouristParam(param, bridgeParam)
    Bridge.callByJS(finalParam)
  })
}

/**
 * 经验值查询
 * @param  {Object} params
 * @return {[type]}      [description]
 */
RemoteDAO.callUC12000306 = function (args) {
  return new Promise((resolve, reject) => {
    Bridge.callByJS({
      callback: function (response) {
        if (response.error === '1') {
          console.error('12000306-error:', response)
          reject(new Error(response.data))
        } else {
          var result = decrypt.json2(response.data)
          var json = JSON.parse(result)
          response.data = json
          console.log('12000306-data', response)
          resolve(response)
        }
      },
      'id': 'nrng_yh',
      'tranCode': 'UC12000306',
      'jsToken': '111',
      'isEncrypt': 'false',
      'transmitMode': 'get',
      'param': {
        'FUNC_ID': '12000306',
        'OP_BRANCH_NO': '0',
        'OP_SITE': '127.0.0.1',
        'OP_PROGRAM': '',
        'BRANCH_NO': '0',
        'PASSWORD': '',
        'USER_CODE': args.userCode + '',
        'USER_TOKEN': '',
        'TOKEN_SERIAL_NO': '0',
        'ACTIVITY_CODE': '201709_GLDH',
        'WALLET_CODE': 'WYJYZ'
      },
      'localParameter': {
        'mobile': 'phone_no',
        'password': 'stock_pwd'
      }
    })
  })
}

RemoteDAO.getNrngHeroList = function (params) {
  return new Promise((resolve, reject) => {
    Vue.prototype.$http({
      url: 'https://api.app.gtja.com/gt/nrng/getNrngHeroList',
      method: 'post',
      headers: {
        'Content-Type': 'application/json'
      },
      data: params
    }).then(response => {
      if (response.data.resultCode === '000000') {
        resolve(response.data)
      }
    }).catch(error => {
      reject(new Error(error))
    })
  })
}

/*
 * 给usercode加密
 */
RemoteDAO.decodeUsercode = function () {
  return new Promise((resolve, reject) => {
    Bridge.callByJS({
      callback: function (response) {
        if (response.error === '1') {
          reject(new Error(response.data))
        } else {
          var result = decrypt.json2(response.data)
          var json = JSON.parse(result)
          response.data = json
          resolve(response.data.body.encrypted_usercode)
        }
      },
      'id': 'nrng',
      'tranCode': 'ENCRYPTPWD',
      'jsToken': '111',
      'isEncrypt': 'false',
      'transmitMode': 'get',
      'param': {
        'user_code': sessionDAO.getUserCode() || ''
      }
    })
  })
}

export default RemoteDAO

